package com.tieto.file.model;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.IteratorUtils;

import com.google.common.net.MediaType;
import com.tieto.repository.EntityFactory;
import com.tieto.user.model.User;
import com.tieto.user.model.UserFactory;
import com.tieto.user.repository.UserRepository;

public class FileFactory implements EntityFactory<File, Long> {
	private static final String FILE_CONTENT = "fileContent";
    private UserRepository userRepository;

    public FileFactory(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
	@Override
	public List<File> getEntities(int count) {
        User user = createOrGetUser();
        List<File> entities = new ArrayList<File>();
		for (int i = 0; i < count; i++) {
			File file = new File("filename" + i,
					MediaType.PLAIN_TEXT_UTF_8.toString(),
					FILE_CONTENT.getBytes());
			file.setSize(Long.valueOf(FILE_CONTENT.length()));
			file.setCreateTime(Long.valueOf(i));
			file.setOwner(user);
			entities.add(file);
		}
		return entities;
	}
	private User createOrGetUser() {
        @SuppressWarnings("unchecked")
        List<User> users = IteratorUtils.toList(userRepository.findAll().iterator());
        User user;
        if (!users.isEmpty()) {
            user = users.get(0);
        }else {
            UserFactory userFactory = new UserFactory();
            user = userFactory.getEntities(1).get(0);
            userRepository.save(user);
        }
        return user;
    }	
	@Override
	public File getUpdatedEntity(File entity) {
		File file = new File(entity.getFilename() + "_updated",
				MediaType.HTML_UTF_8.toString(),
				(entity.getContent() + "updated").getBytes());
		file.setCreateTime(entity.getCreateTime() + 1);
		file.setSize(entity.getSize() + 1);
		file.setOwner(entity.getOwner());
//		file.setOwner(userFactory.getUpdatedEntity(file.getOwner()));
		return file;
	}
}
